package web.servlet;

import domain.Account;
import domain.Cart;
import domain.Item;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.LogService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

public class RemoveCartItemServlet extends HttpServlet {

    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        String workingItemId = req.getParameter("workingItemId");

        Item item = cart.removeItemById(workingItemId);

        if(item == null) {
            session.setAttribute("errorMsg","Attempted to remove null CartItem from Cart. ");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        } else {

            if(req.getParameter("record")!=null&&(Account)session.getAttribute("loginAccount")!=null){
                LogService logService = new LogService();
                Account account=(Account)session.getAttribute("loginAccount");
                String userid=account.getUsername();
                String action=req.getParameter("record")+workingItemId;

                Calendar rightNow = Calendar.getInstance(); // 子类对象
                int year = rightNow.get(Calendar.YEAR);
                int month = rightNow.get(Calendar.MONTH)+1;
                int date= rightNow.get(Calendar.DATE);
                int hour = rightNow.get(Calendar.HOUR_OF_DAY);
                String dates=year+"."+month+"."+date+" "+hour+"h";

                System.out.println(userid+" "+action);
                logService.record(userid,action,dates);

            }

            PrintWriter out = resp.getWriter();
            out.print(cart.getSubTotal());

//            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }
    }


}
